const { app, BrowserWindow, ipcMain, Tray, Menu } = require('electron')
const path = require('path')
const {
  createUserInfoFolder,
  setChatRecord,
  getChatRecord,
} = require('./func.cjs')

// 定义主程序窗口
let mainWindow
// 创建主程序窗口
const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 600,
    // alwaysOnTop: true,
    // x: 1600,
    // y: 100,
    // transparent: true,
    // backgroundColor: '#F5F7FA',
    frame: false,
    resizable: true,
    icon: path.join(__dirname, '../public/processHarvest.png'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      devTools: true, //客户端能否打开开发者工具（快捷键：ctrl+shift+i）
    },
  })

  // 设置窗口的最小尺寸
  mainWindow.setMinimumSize(960, 600)
  mainWindow.loadURL('http://127.0.0.1:7012/')
  // mainWindow.webContents.toggleDevTools()

  mainWindow.on('close', (event) => {
    if (!app.isQuiting) {
      event.preventDefault()
      mainWindow.hide()
    }
    // 返回 false ，阻止默认关闭行为
    return false
  })
}

app.whenReady().then(() => {
  createWindow()
  createTrayIcon()
})
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// 主程序窗口最小化
ipcMain.on('min-window', () => mainWindow.minimize())
// 切换主窗口最大化
ipcMain.on('max-window', () => {
  if (mainWindow.isMaximized()) mainWindow.unmaximize()
  else mainWindow.maximize()
})
// 确认是否关闭主程序窗口
ipcMain.on('close-window', () => mainWindow.close())

//
//
// 托盘
let tray = null
// 创建托盘图标，以及菜单栏
function createTrayIcon() {
  if (!tray)
    tray = new Tray(path.join(__dirname, '../public/processHarvest.png'))

  const contextMenu = Menu.buildFromTemplate([
    { label: '显示app', click: () => mainWindow.show() },
    {
      label: '退出app',
      click: () => {
        app.isQuiting = true
        app.quit()
      },
    },
  ])

  tray.setToolTip('历程收获')
  tray.setContextMenu(contextMenu)
  tray.on('click', () => mainWindow.show())
}

//
//
// 阅读窗口
let readingWindow = null
// 创建阅读窗口函数
const createReadingWindow = async () => {
  // 计算父窗口位置，使得子窗口出现在父窗口正中央
  let parent_x = mainWindow.getPosition()[0]
  let parent_y = mainWindow.getPosition()[1]
  let parent_size_x = mainWindow.getSize()[0]
  let parent_size_y = mainWindow.getSize()[1]
  let settings_size_x = 900
  let settings_size_y = 420
  let settings_new_x = parent_x + (parent_size_x - settings_size_x) / 2
  let settings_new_y = parent_y + (parent_size_y - settings_size_y) / 2

  const _x = parseInt(settings_new_x)
  const _y = parseInt(settings_new_y)

  readingWindow = new BrowserWindow({
    width: 1200,
    height: 420,
    x: _x,
    y: _y,
    frame: false,
    resizable: true,
    icon: path.join(__dirname, '../public/processHarvest.png'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      devTools: true, //客户端能否打开开发者工具（快捷键：ctrl+shift+i）
    },
  })
  readingWindow.setMinimumSize(900, 420)
  await readingWindow.loadURL('http://127.0.0.1:7013')
  // readingWindow.loadFile(path.join(__dirname, 'close.html'))
  // readingWindow.webContents.toggleDevTools()
}

// 创建或者打开阅读窗口
ipcMain.on('r-open-window', async (event, data) => {
  if (readingWindow) {
    await readingWindow.show()
    readingWindow.webContents.send('harvest-info', data)
    return
  }

  await createReadingWindow()
  setTimeout(() => {
    readingWindow.webContents.send('harvest-info', data)
  }, 2000)
})
// 关闭阅读程序窗口
ipcMain.on('r-close-window', () => {
  readingWindow.close()
  readingWindow = null
})
// 阅读程序窗口最小化
ipcMain.on('r-min-window', () => readingWindow.minimize())
// 切换阅读窗口最大化
ipcMain.on('r-max-window', () => {
  if (readingWindow.isMaximized()) readingWindow.unmaximize()
  else readingWindow.maximize()
})

//
//
// 控制本地文件
// 创建用户本地文件信息目录
ipcMain.on('f-create-dir', (_, account) => createUserInfoFolder(account))
// 将用户聊天记录追加到json文件中
ipcMain.on('f-set-chatting', (_, data) => {
  const { account, chatRecord, receiverId } = data
  setChatRecord(account, chatRecord, receiverId)
})
// 获取聊天记录，并将聊天记录数据返回给渲染进程
ipcMain.on('f-get-chatting', (_, data) => {
  const { account, receiverId } = data
  const d = getChatRecord(account, receiverId)
  mainWindow.webContents.send('f-send-chatting', d)
})
